package com.oocl.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

import com.oocl.constant.LogLevel;
import com.oocl.operation.OnlineUserDao;
import com.oocl.operation.UserThreadOperation;
import com.oocl.operation.impl.OnlineUserDaoImpl;
import com.oocl.operation.impl.UserTheadOpetationImpl;
import com.oocl.util.ConsoleLogUtil;
import com.oocl.util.ResourceCloser;

public class ChatServer {
	private ServerSocket server=null;
	private boolean isRunning = true;
	private long start;
	private long end;
	
	public void start(){
		start = System.currentTimeMillis();
		new Thread(){

			@Override
			public void run() {
				while(isRunning){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					end = System.currentTimeMillis();
				}
			}
			
		}.start();
		try {
			server = new ServerSocket(8888);
			ConsoleLogUtil.log("Chat server start success...", LogLevel.INFO);
			while(isRunning){
				Socket socket = server.accept();
				ConsoleLogUtil.log("A user connected to the server", LogLevel.INFO);
				new UserThread(socket).start();
			}
		} catch (IOException e) {
			ConsoleLogUtil.log("Chat server start wrong!"+e.getMessage(), LogLevel.ERROR);
			ResourceCloser.release(null, null, null, server);
		}finally {
			ResourceCloser.release(null, null, null, server);
			ConsoleLogUtil.log("Chat server stop success...", LogLevel.INFO);
		}
	}
	
	public void close(){
		try {
			UserThreadOperation operation = new UserTheadOpetationImpl();
			OnlineUserDao userDao = new OnlineUserDaoImpl();
			Map<String, UserThread> threads = operation.findAll();
			for(String name:threads.keySet()){
				userDao.delete(name);
				threads.get(name).getSocket().close();
				threads.get(name).setRunning(false);
			}
			this.isRunning = false;
			ResourceCloser.release(null, null, null, server);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}

	public boolean isRunning() {
		return isRunning;
	}
	
	public long getRunningTime(){
		return end-start;
	}
	
}
